package com.xsf.pay.common.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.cache.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义cacheManager
 *
 * @author 18961
 */
public class RedisCacheManagerCustomize extends RedisCacheManager {
    private final static String PREFIX = "bart:spring:cache:";

    public final static CacheKeyPrefix CACHE_KEY_PREFIX = new CacheKeyPrefix() {

        @NotNull
        @Override
        public String compute(@NotNull String cacheName) {
            return PREFIX + cacheName + ":";
        }

    };

    protected final static Map<String, Duration> CACHE_NAME_MAP = new HashMap<>();

    public RedisCacheManagerCustomize(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @NotNull
    @Override
    protected RedisCache createRedisCache(@NotNull String name, RedisCacheConfiguration cacheConfig) {
        return super.createRedisCache(name, copyCacheConfiguration(name, cacheConfig));
    }

    protected RedisCacheConfiguration copyCacheConfiguration(String name, RedisCacheConfiguration cacheConfig) {
        if (null != cacheConfig) {
            if (CACHE_NAME_MAP.containsKey(name)) {
                return cacheConfig.entryTtl(CACHE_NAME_MAP.get(name))
                        .computePrefixWith(RedisCacheManagerCustomize.CACHE_KEY_PREFIX);
            }
        }
        return cacheConfig;
    }
}
